package com.sluggard.ai.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.reflect.TypeToken;
import com.sluggard.ai.manage.DynamicMcpManager;
import com.sluggard.common.model.res.Result;
import com.sluggard.common.utils.GsonUtil;
import io.modelcontextprotocol.client.McpAsyncClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import jakarta.annotation.Resource;
import org.springframework.ai.mcp.client.autoconfigure.properties.McpStdioClientProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 类描述：
 *
 * @author lizheng
 * @created 2025/4/27 15:47
 */
@RestController
@RequestMapping(value ="/mcp")
public class  McpController {

    @GetMapping(value ="/list")
    public Result list(){
        return Result.ok(DynamicMcpManager.getMcpAsyncClients().stream().map(item -> {
            System.out.println(item);
            return item.getServerInfo().name();
        }).toList());
    }

    @PostMapping(value =  "/update")
    public Result update(@RequestParam(value = "file") MultipartFile file) {
        // 文件校验 仅允许上传json文件
        if (!Objects.requireNonNull(file.getOriginalFilename()).endsWith(".json")) {
            return Result.error("文件格式错误");
        }
        // 读取文件内容
        try {
            String content = new String(file.getBytes());
            Map<String, Map<String, McpStdioClientProperties.Parameters>> mcpServersMap = GsonUtil.fromJson(content, new TypeToken<Map<String, Map<String, McpStdioClientProperties.Parameters>>>() {
            }.getType());
            Map<String, McpStdioClientProperties.Parameters> mcpServers = mcpServersMap.get("mcpServers");
            DynamicMcpManager.updateServers(mcpServers);
            return Result.ok();
        } catch (Exception e) {
            return Result.error("文件解析错误");
        }
    }

}
